package com.tg.app.activity.device.add;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.core.util.Consumer;

import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.config.ApiUrl;
import com.base.BaseActivity;
import com.tange.core.backend.service.response.RxResponse;
import com.tange.core.data.structure.Ret;
import com.tange.core.device.manage.DeviceRename;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.device.info.DeviceInfoServiceManager;
import com.tg.app.R;
import com.tg.app.TGSdk;
import com.tg.app.activity.device.DeviceListActivity;
import com.tg.app.report.DeviceAddReport;
import com.tg.app.report.DeviceAddReportBean;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.sdk.TGMessageType;
import com.tg.data.http.entity.ChangeDeviceNameBean;
import com.tg.network.http.TimeZoneUtils;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class ApSetNameActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "ApSetNameActivityTAG";

    private EditText editText;
    private long mDeviceID = 0;
    private int mAuthStatus;
    private String mIccId;
    private String uuid;
    private Button button;
    private static final int SET_NAME_SUCCESS = 0;
    private int freeCombo = 1;
    private String mDeviceType;
    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == SET_NAME_SUCCESS) {
                int result = msg.arg1;
                String name  = editText.getText().toString().trim();
                if (result == 1) {
                    TGToast.showToast(R.string.setting_success);
                } else {
                    TGToast.showToast(R.string.setting_fail);
                    name = "";
                }
                DeviceAddReportBean bean = DeviceAddReport.getInstance().getReportBean();
                if (bean!=null){
                    bean.endTime = System.currentTimeMillis();
                    DeviceAddReport.getInstance().setReportBean(bean);
                    bean.isSucceed = true;
                    DeviceAddReport.getInstance().upload();
                }
                TGLog.i(TAG,"SET_NAME_SUCCESS :");
                boolean isThirdApp = TGSdk.getInstance().isThirdPartyApp();
                TGLog.i(TAG, "handleMessage: isThirdApp = " + isThirdApp);
                if (isThirdApp){
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put(TGSdk.KEY_UUID, getIntent().getStringExtra(ApiUrl.DEVICE_UUID));
                        jsonObject.put(TGSdk.KEY_NAME, name);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String param = jsonObject.toJSONString();
                    TGLog.i(TAG,"param = " + param);
                    TGSdk.getInstance().notifyThirdPartyApp(TGMessageType.MSG_ADD_DEVICE_SUCCUSS, param);
                    finish();
                }else{
                    gotoActivity();
                }
            }
            return false;
        }
    });

    private void gotoActivity() {
        Intent intent = new Intent();

        if (mAuthStatus == 1) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(ApiUrl.DEVICEID, mDeviceID);
            intent.putExtra(ApiUrl.DEVICE_AUTH, mIccId);
            intent.setClass(getBaseContext(), TipDialogActivity.class);
            startActivity(intent);
        } else {
            intent.setClass(getBaseContext(), DeviceListActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            if (freeCombo==0){
                intent.putExtra(AddFragmentTabActivity.EXT_DEVICE_ADD_QRCODE_SUCCEDD_ID, mDeviceID);
                intent.putExtra(ApiUrl.DEVICE_TYPE, mDeviceType);
                intent.putExtra(ApiUrl.DEVICE_UUID, uuid);
            }
            startActivity(intent);
            finish();
        }

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.fragment_ap_set_name);
        hideActionBar();
        initView();

        mDeviceID = getIntent().getLongExtra(ApiUrl.DEVICEID, 0);
        mAuthStatus = getIntent().getIntExtra(ApiUrl.DEVICE_AUTH, 0);
        mIccId = getIntent().getStringExtra(ApiUrl.DEVICE_ICCID);
        freeCombo = getIntent().getIntExtra(AddFragmentTabActivity.EXT_SIM_FREE_COMBO,1);
        uuid = getIntent().getStringExtra(ApiUrl.DEVICE_UUID);
        mDeviceType = getIntent().getStringExtra(ApiUrl.DEVICE_TYPE);

        setTimezone();
    }


    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }


    private void setTimezone() {
        TimeZoneUtils.setTimezone(uuid);
    }

    private void setDeviceName() {
        if (CameraHub.getInstance().isEnableLocalApConnect()) {
            return;
        }

        String name = editText.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            return;
        }

        DeviceRename.INSTANCE.require(uuid, name, new Consumer<Ret>() {
            @Override
            public void accept(Ret ret) {
                if (ret.getSuccess()) {
                    TGLog.i(TAG, "[request] success");
                    handler.sendMessage(handler.obtainMessage(SET_NAME_SUCCESS, 1, 0));
                } else {
                    TGLog.i(TAG, "[request] fail");
                    handler.sendMessage(handler.obtainMessage(SET_NAME_SUCCESS, 0, ret.getCode()));
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_add_finish) {
            setDeviceName();
        }
    }

    @Override
    protected void initView() {
        editText = findViewById(R.id.device_ap_add_set_device_name);
        button = findViewById(R.id.btn_add_finish);
        button.setOnClickListener(this);
        button.setAlpha(0.4f);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    button.setAlpha(0.4f);
                } else {
                    button.setAlpha(1f);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onBackPressed() {
    }
}
